import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;
import JavaBean.User;
/**
 * @author Sai
 * Created by Sai on 2019-03-03.
 */
@SuppressWarnings("Duplicates")
@WebServlet(urlPatterns = {"/Regist"})
public class Regist extends HttpServlet {

    @Override

    protected void service(HttpServletRequest request, HttpServletResponse response) throws  IOException {
        int i;
        try {
            request.setCharacterEncoding("UTF-8");
            String user = request.getParameter("username");
            String sno = request.getParameter("stunumber");
            String Password = request.getParameter("pa");
            String Email = request.getParameter("email");
            String PersonMessage = null;
            String root = System.getProperty("user.dir");
            String FileName="Usermessage.txt";
            String filepath = root+File.separator+FileName;
            FileReader fd = new FileReader(filepath);
            BufferedReader reader = new BufferedReader(fd);
            while((PersonMessage = reader.readLine())!=null) {
                String message[] = PersonMessage.split(" ");
                if (message[0].equals(user)) {
                    JOptionPane.showMessageDialog(null, "该用户已存在", " 请重新注册", JOptionPane.ERROR_MESSAGE);
                    response.sendRedirect("/register.jsp");
                }
            }
            fd.close();
            reader.close();
            HttpSession session = request.getSession();
            FileWriter fd1 = new FileWriter(filepath,true);
            BufferedWriter writer = new BufferedWriter(fd1);
            String img= "picture/"+sno+".jpg";
            writer.write(user + " " + Email + " " + Password + " " + img + " " + sno + "\n");
            writer.flush();
            writer.close();
            User userr = new User( user, Email,Password,img,sno);
            session.setAttribute("user",userr);
            response.sendRedirect("UserPage.jsp");
            fd1.close();
            writer.close();
        }
        catch(IOException e){
            response.sendRedirect("/error.jsp");
        }
    }
}
